################################################################################
# Replication
# Title:
# Authors:
################################################################################


################################################################################
# Loading packages -------------------------------------------------------------

if(require(tidyverse) == F) {install.packages("tidyverse"); require(tidyverse)}
if(require(did) == F) {install.packages("did"); require(did)}
if(require(ggplot2) == F) {install.packages("ggplot2"); require(ggplot2)}
if(require(scales) == F) {install.packages("scales"); require(scales)}
if(require(patchwork) == F) {install.packages("patchwork"); require(patchwork)}
if(require(ggeffects) == F) {install.packages("ggeffects"); require(ggeffects)}
if(require(modelsummary) == F) {install.packages("modelsummary"); require(modelsummary)}
if(require(gt) == F) {install.packages("gt"); require(gt)}


################################################################################
# Setting the working directory ----------------------------------------------------
setwd("")
# Folder for load the data and uploading figures and tables:
outfolder <- ""

################################################################################
# Loading the datasets ---------------------------------------------------------
load(file.path(outfolder, 'replication.data.RData'))

################################################################################
# Visualization of parallel trends ------------------------------------------------


# The following function creates tables for the average outcome of each election:
get.pre.tab <- function(data, outvar){
  
  # `data` is the gender or race dataset 
  # `outvar` is the outcome 
  
  # Table for federal level:
  tab <- data %>% 
    filter(office=='Federal Deputy') %>% 
    # Getting the average outcome by electoral year:
    lm(as.formula(paste(outvar, "~ election.year")), data = .) %>% 
    # Getting the predicted value:
    predict_response(., terms = c('election.year')) %>%
    data.frame() %>% mutate(group='Federal level')
  
  # The same is done at the state level:
  tab <- data %>% filter(office=='State Deputy') %>% 
    lm(as.formula(paste(outvar, "~ election.year")), data = .) %>% 
    predict_response(., terms = c('election.year')) %>%
    data.frame() %>% mutate(group='State level') %>% 
    rbind(tab)
  
  return(tab)
}

# The following function creates graphs for the average outcome of each election  
get.pre.graph <- function(tab, outlabel, grouptitle){
  # `tab` is the table got from previous `get.pre.tab` function
  # `outlabel` is the label for outcome that will display in graph  
  # `grouptitle` is the title that will describe gender or race 
  g <- tab %>% 
    ggplot(., aes(x=x, y=predicted, shape = group, group = group)) +
    geom_line() + 
    geom_point() + 
    geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = 0.1) +
    scale_y_continuous(labels =percent) +
    ylab(outlabel) +
    ggtitle(grouptitle) +
    theme_bw() +
    theme(legend.position="bottom",
          legend.title = element_blank(),
          axis.title.x = element_blank(),
          plot.title = element_text(hjust = 0.5)) 
  
  return(g)
}

# Use the previous functions to get each graph.
# Gender
pre.g.gen.cand <- get.pre.tab(test.data.gen, 'cand.share') %>%
  get.pre.graph(., "Candidates (%)", "Gender")
pre.g.gen.fund <- test.data.gen %>% 
  filter(as.numeric(election.year)>=2018) %>%
  get.pre.tab(., 'fund.share') %>%
  get.pre.graph(., "Funding (%)", "Gender")
pre.g.gen.vote <- get.pre.tab(test.data.gen, 'vote.share') %>%
  get.pre.graph(., "Votes (%)", "Gender")
pre.g.gen.elec <- get.pre.tab(test.data.gen, 'elect.share') %>%
  get.pre.graph(., "Elected (%)", "Gender")
# Race
pre.g.race.cand <- get.pre.tab(test.data.race, 'cand.share') %>%
  get.pre.graph(., "Candidates (%)", "Race")
pre.g.race.fund <- test.data.race %>% 
  filter(as.numeric(election.year)>=2018) %>%
  get.pre.tab(., 'fund.share') %>%
  get.pre.graph(., "Funding (%)", "Race")
pre.g.race.vote <- get.pre.tab(test.data.race, 'vote.share') %>%
  get.pre.graph(., "Votes (%)", "Race")
pre.g.race.elec <- get.pre.tab(test.data.race, 'elect.share') %>%
  get.pre.graph(., "Elected (%)", "Race")


# Combining the graphs and saving them.
# Party efforts to support candidacies:
(pre.g.gen.cand + pre.g.gen.fund) /
  (pre.g.race.cand + pre.g.race.fund)
# Saving
ggsave(file.path(outfolder, 'party.trends.png'), width = 10, height = 5)

# Electoral performance of candidates:
(pre.g.gen.vote + pre.g.gen.elec) / 
  (pre.g.race.vote + pre.g.race.elec)
# Saving
ggsave(file.path(outfolder, 'perform.trends.png'), width = 10, height = 5)


################################################################################
### Summary statistics ---------------------------------------------------------

# Summary statistics by gender

# Separeting the approprieate data:
desc.gen <- test.data.gen %>% 
  # Saving in the output folder:desc.gen <- test.data.gen %>% 
  mutate(post=ifelse(election.year=='2022', 1, 0), # Post-treatment period = 1, otherwise = 0
         treatgroup=ifelse(office=='Federal Deputy', 1, 0)) %>% # Treatment group = 1, otherwise = 0
  # Select treatment and time-period variables, outcomes and covariates:
  select(post, treatgroup, 
         cand.share, fund.share, vote.share, elect.share,
         incumb.share, coll.degree.share) 

# Variable labels:
new_names <- c("Post treatment period", "Treatment group",
               'Candidates', 'Funding',
               'Vote share', 'Elected candidates', 'Female incumbents',
               'Women with college degree')

# Getting final table:
desc.gen %>% 
  # Rename variables with new labels:
  rename_with(~set_names(new_names)) %>% 
  # Getting summary statistics with modelsummary package:
  datasummary_skim(., fmt = 3, output = 'gt', histogram = F) %>% 
  # Title and footnote:
  tab_header(title = md("Summary statistics of variables by gender")) %>% 
  tab_footnote(footnote = "Notes: For each variable, the table displays the mean, 
  standard deviation, minimum, median, and maximum.") %>% 
  # Improving the appearance of the table:
  tab_options(heading.title.font.size=16) %>% 
  opt_vertical_padding(scale = 0) %>% 
  cols_hide(columns = c(2,3)) %>% 
  gtsave(filename = file.path(outfolder, "tab.summary.gen.tex"))



# Summary statistics by race
# As follows, the same steps will be applied to obtain summary statistics for race.

# Separete approprieate data:
desc.race <- test.data.race %>% 
  mutate(post=ifelse(election.year=='2022', 1, 0),
         treatgroup=ifelse(office=='Federal Deputy', 1, 0)) %>% 
  select(post, treatgroup, 
         cand.share, fund.share, vote.share, elect.share,
         incumb.share, coll.degree.share) 

# Table variable labels
new_names <- c("Post treatment period", "Treatment group",
               'Candidates', 'Funding',
               'Vote share', 'Elected candidates', 'Female incumbents',
               'Afro-Brazilians with college degree')

# Getting final table:
desc.race %>% 
  # improving variable names:
  rename_with(~set_names(new_names)) %>% 
  # Getting summary statistics with datasummary:
  datasummary_skim(., fmt = 3, output = 'gt', histogram = F) %>% 
  # Title and footnote:
  tab_header(title = md("Summary statistics of variables by race")) %>% 
  tab_footnote(footnote = "Notes: For each variable, the table displays the mean, 
  standard deviation, minimum, median, and maximum.") %>% 
  # Improving the appearance of the table:
  tab_options(heading.title.font.size=16) %>% 
  opt_vertical_padding(scale = 0) %>% 
  cols_hide(columns = c(2,3)) %>% 
  # saving in the `outputs` folder:
  gtsave(filename = file.path(outfolder, "tab.summary.race.tex"))


################################################################################
###### DiD C&S------------------------------------------------------------------
# This section runs the mean results.
# The coefficients were estimated with did package by Callaway and Santana

# Following two functions are useful to get models and tables with mean results

# `get.did.mods` runs tests for several outcomes and specifications 
get.did.list <- function(did.data, outvars, covariates="no.covariates"){
  
  # `did.data` is the data in the format required by `att_gt` function from `did` package
  # `covariates` is a specification for tests without ("no.covariates") or with covariates ("covariates"). The two options runs doubly-robust estimation method
  # `outvars` is a character vector with the covariate names
  
  if(covariates=="no.covariates"){covs <- as.formula("~1")}
  if(covariates!="no.covariates"){covs <- as.formula("~incumb.share+coll.degree.share")}

  mod.list <- list()
  for(i in 1:length(outvars)){
    
    # Getting models' outputs:
    mod.did <- did.data %>%
      filter(!is.na(!!sym(outvars[i]))) %>% # Get rid of NA values from dependent variable. 
                                            # The function do it anyway, but this procedure avoids the use of non-existent time-periods
      att_gt(yname = outvars[i], gname = "treatment", idname = "id", tname = "time",
             xformla = covs, data = .)
    
    mod.list[[i]] <- mod.did
    names(mod.list)[[i]] <- outvars[i] # rename the model with the covariate label
    
  }
  return(mod.list)
}


# `get.did.tab` gets main results from a model list 
get.did.tab <- function(mod.list){
  # `mod.list` is a list with did models
  
  for(i in 1:length(mod.list)){
    # Getting agregated results:
    x <- mod.list[[i]] %>% aggte(type = 'simple')
    # option "simple" computes a weighted average of all group-time average treatment effects 
    # with weights proportional to group size
    
    out.tab <- data.frame(ATT=x$overall.att,
                          Std.Error=x$overall.se,
                          conf.low=x$overall.att-(1.96*x$overall.se),
                          conf.high = x$overall.att+(1.96*x$overall.se),
                          N=x$DIDparams$n)
    # Note: Confidence intervals have gotten manually, as ATT - (1.96 * se), 
    # because values from `tidy` function do not correspond with confidence intervals
    # from `aggte` function (did package). To check and compare, run:
    # aggte(mod.gen.cand, type = 'simple')
    # tidy(mod.gen.cand)
    
    out.tab <- out.tab %>% 
      # Check statistical significance with at 95% confidence level:
      mutate(sig=ifelse(ATT>0 & conf.low>0 & conf.high>0, "*", ""),
             sig=ifelse(ATT<0 & conf.low<0 & conf.high<0, "*", sig))  %>% 
      # Rounding:
      mutate(ATT=round(ATT, 3), 
             ATT=paste0(ATT, sig),
             Std.Error=round(Std.Error, 3), 
             Std.Error=paste0("(", Std.Error, ")")) %>% 
      # Changing outcome variable lables:
      mutate(outvar=names(mod.list)[[i]]) %>% 
      select(outvar, ATT, Std.Error, N)
    
    if(i==1){did.out.tab <- out.tab}else{did.out.tab <- rbind(did.out.tab, out.tab)}
  }
  return(did.out.tab)
}

### Tests  ---------------------------------------------------------------------

# Getting test data:
test.data.cs <- test.data.gen %>% 
  mutate(treatment=ifelse(office=="Federal Deputy", 1, 0), # Treatment group is 1 for federal level
         time=as.numeric(election.year), # Time periods
         id=paste(party, "_", state, "_", office), # Observations are represented by party p in district d in the federation level l.
         id=as.numeric(factor(id))) %>% 
  # For did package, all observations from treatment group have to get the value of first time period of intervention.
  # In this case, 2022 year. Otherwise, the variable assumes value 0
  mutate(treatment=ifelse(treatment==1, 2022, 0))

# Running the models for gender:
outvars <- c('cand.share', 'fund.share', 'vote.share', 'elect.share')
mod.list.gen <- get.did.list(test.data.cs, outvars = outvars, covariates = "no.covariates")
# Obs: The massage "No pre-treatment periods to test" shows up because 
# there are NA values for funding share in electoral years previously to 2018.
# 2018 elections is the only pre-treatment period. 

# Getting interest coefficients:
did.out.tab.gen <- get.did.tab(mod.list.gen)
did.out.tab.gen <- did.out.tab.gen %>%
  t() %>% as_tibble() 


### Tests for race
# Same steps had take for race:

# Getting test data:
test.data.cs <- test.data.race %>% 
  mutate(treatment=ifelse(office=="Federal Deputy", 1, 0),
         time=as.numeric(election.year),
         id=paste(party, "_", state, "_", office), 
         id=as.numeric(factor(id))) %>% 
  mutate(treatment=ifelse(treatment==1, 2022, 0))

# Running the models for race:
outvars <- c('cand.share', 'fund.share', 'vote.share', 'elect.share')
mod.list.race <- get.did.list(test.data.cs, outvars = outvars, covariates = "no.covariates")

# Getting interest coefficients:
did.out.tab.race <- get.did.tab(mod.list.race)
did.out.tab.race <- did.out.tab.race %>%
  t() %>% as_tibble() 


# From `did.out.tab.gen` and `did.out.tab.race` tables, Latex tables will be set for the paper as following.


# Parties' efforts --------------------------------------

# Selecting interest outcomes
part.effect <- did.out.tab.gen[-1, c(1, 2)] %>% 
  cbind(did.out.tab.race[-1, c(1, 2)] ) %>%
  data.frame() %>%
  mutate(V0=c('Reform in 2022', "", "N")) %>% 
  select(V0, V1, V2, V1.1, V2.1)

# Replacing outcomes' lables:
names(part.effect) <- c("X", "Candidates", "Funding", "Candidates ", "Funding ")

# Getting Latex table:
part.effect %>% 
  as.tbl() %>% 
  rename_with(~ str_replace_all(., "\\.|X", " ")) %>% 
  gt() %>%  
  tab_spanner(label = "Female", columns = 2:3) %>%
  tab_spanner(label = "Afro-Brazilian", columns = 4:5) %>%
  tab_header(title = 'Effect of funding incentives on party efforts to support female and afro-Brazilian candidacies') %>% 
  # Notes:
  tab_footnote(footnote = "Notes: * p < 0.05, ** p < 0.01, *** p < 0.001.
  The tests were conducted using the Differences-in-Differences. 
  The estimated effects show the impact of  incentives approved by the 2022 reform on 
  political parties' efforts to promote female and afro-Brazilian candidates. 
  The dependent variables include the proportion of female and afro-Brazilian 
  candidates within party lists, as well as the campaign funding allocated 
  by parties to those candidates.
  The coefficients were estimatted with did R package (Callaway & Sant'Anna, 2021).
               ") %>% 
  tab_options(heading.title.font.size = 16) %>% 
  opt_vertical_padding(scale = 0) %>% 
  gtsave(filename = file.path(outfolder, "tab.effort.tex"))

# Check the table:
part.effect


# Female and Afro-Brazilian electoral performance ------------------------------

# Selecting interest outcomes
part.effect <- did.out.tab.gen[-1, c(3, 4)] %>% 
  cbind(did.out.tab.race[-1, c(3, 4)] ) %>%
  data.frame() %>%
  mutate(V0=c('Reform in 2022', "", "N")) %>% 
  select(V0, V3, V4, V3.1, V4.1)

# Replacing outcomes' lables:
names(part.effect) <- c("X", "Votes", "Elected", "Votes ", "Elected ")

# Getting Latex table:
part.effect %>% 
  as.tbl() %>% 
  rename_with(~ str_replace_all(., "\\.|X", " ")) %>% 
  gt() %>%  
  tab_spanner(label = "Female", columns = 2:3) %>%
  tab_spanner(label = "Afro-Brazilian", columns = 4:5) %>%
  tab_header(title = 'Effect of  on electoral performance ofwomen and Afro-Brazilians') %>% 
  # Notes:
  tab_footnote(footnote = "Notes: * p < 0.05, ** p < 0.01, *** p < 0.001.
  The tests were conducted using the Differences-in-Differences. 
  The estimated effects show the impact of  approved by the 2022 reform on 
  electoral performance of female candidates. 
  The dependent variables are the vote share and the number of elected candidates for women and Afro-Brazilians. 
  The coefficients were estimatted with did R package (Callaway & Sant'Anna, 2021).
  ") %>% 
  tab_options(heading.title.font.size = 16) %>% 
  opt_vertical_padding(scale = 0) %>% 
  gtsave(filename = file.path(outfolder, "tab.perform.gen.race.tex"))

# Check the table:
part.effect

### Grapths --------------------------------------------------------------------

# Following function build standardized graphs for each outcome:
get.did.graph <- function(model, ylabel){
  
  did.graph <- model %>% 
    aggte(., type='dynamic') %>% # computes average effects across different 
    #lengths of exposure to the treatment
    tidy() %>% 
    mutate(time=as.character(2022+as.numeric(event.time))) %>% # Replacing time generated by did package for electoral year.
    ggplot(., aes(x = time, y = estimate)) +
    geom_point(aes(color = time == "2022"), size = 3) +  
    geom_errorbar(aes(ymin = conf.low, ymax = conf.high, color = time == "2022"), width = 0.2) + 
    scale_color_manual(values = c("TRUE" = "brown4", "FALSE" = "gray30"), labels = c("Pre", "Post")) + 
    theme_minimal() +
    labs(x = "Electoral year", y = ylabel) +
    geom_hline(yintercept = 0, linetype = "dashed", color = "black") + 
    geom_text(aes(label=paste0(round(model$att*100, 2), "%")), 
              position = position_dodge(1.4), 
              size = 3.3, vjust=-0.2, hjust=-0.05, colour = "black") +
    theme(axis.title = element_text(face = 'plain', colour="black", size=10),
          axis.ticks = element_blank(),
          axis.text.y = element_blank(),
          panel.grid.major.y = element_blank(),
          legend.position = 'bottom',
          legend.title = element_blank())
  
  if(length(model$att)==1){
    did.graph <- did.graph +
      scale_color_manual(values = c("TRUE" = "brown4", "FALSE" = "gray30"), labels = c("Post"))
  }
  
  return(did.graph)
}


# Getting graphs for each outcome

g.gen.cand <- get.did.graph(mod.list.gen[[1]], "Male candidates (%)")
g.gen.fund <- get.did.graph(mod.list.gen[[2]], "Funding for women (%)")
g.gen.vote <- get.did.graph(mod.list.gen[[3]], "Votes for women (%)")
g.gen.elec <- get.did.graph(mod.list.gen[[4]], "Elected women (%)")

g.race.cand <- get.did.graph(mod.list.race[[1]], "Afro-Brazilian candidates (%)")
g.race.fund <- get.did.graph(mod.list.race[[2]], "Funding for Afro-Brazilians (%)")
g.race.vote <- get.did.graph(mod.list.race[[3]], "Votes for Afro-Brazilians (%)")
g.race.elec <- get.did.graph(mod.list.race[[4]], "Elected Afro-Brazilians (%)")

# Gathering graphs regarding parties' efforts to support women and Afro-Brazilians
(g.gen.cand + g.gen.fund) /
  (g.race.cand + g.race.fund)

ggsave(file.path(outfolder, 'part.effort.png'), width = 10, height = 6)

# Gathering graphs regarding electoral performance of women and Afro-Brazilians
(g.gen.vote + g.gen.elec) / 
  (g.race.vote + g.race.elec)

ggsave(file.path(outfolder, 'part.perform.png'), width = 10, height = 6)


################################################################################
###### DiD with covariates -----------------------------------------------------

# In this section, similar tests were ran. The only difference is the addition of
# time variant covariates.

### Tests for gender

# Getting test data:
test.data.cs <- test.data.gen %>% 
  filter(election.year!='2006') %>% # There are just missing covariate values for the first time period
  mutate(treatment=ifelse(office=="Federal Deputy", 1, 0),
         time=as.numeric(election.year),
         id=paste(party, "_", state, "_", office), 
         id=as.numeric(factor(id))) %>% 
  mutate(treatment=ifelse(treatment==1, 2022, 0)) %>% 
  mutate(coll.degree.share=ifelse(is.na(coll.degree.share), 0, coll.degree.share)) 


# Running the models for gender:
outvars <- c('cand.share', 'fund.share', 'vote.share', 'elect.share')
mod.list.gen <- get.did.list(test.data.cs, outvars = outvars, 
                             covariates = "covariates") # Select `covariates` option

# Getting interest coefficients:
did.out.tab.gen <- get.did.tab(mod.list.gen)
did.out.tab.gen <- did.out.tab.gen %>%
  t() %>% as_tibble() 


### Tests for race
# Same steps had take for race

# Getting test data:
test.data.cs <- test.data.race %>% 
  mutate(treatment=ifelse(office=="Federal Deputy", 1, 0),
         time=as.numeric(election.year),
         id=paste(party, "_", state, "_", office), #
         id=as.numeric(factor(id))) %>% 
  mutate(treatment=ifelse(treatment==1, 2022, 0)) %>% 
  mutate(coll.degree.share=ifelse(is.na(coll.degree.share), 0, coll.degree.share)) 

# Running the models for gender:
outvars <- c('cand.share', 'fund.share', 'vote.share', 'elect.share')
mod.list.race <- get.did.list(test.data.cs, outvars = outvars, 
                              covariates = "covariates") # Select `covariates` option

# Getting interest coefficients:
did.out.tab.race <- get.did.tab(mod.list.race)
did.out.tab.race <- did.out.tab.race %>%
  t() %>% as_tibble() 

# From `did.out.tab.gen` and `did.out.tab.race` tables, Latex tables will be set for the paper as following.


# Parties' efforts for female --------------------------------------------------

# Adding lines informing what models' covariates
adlines <- data.frame(V0=c("Incumbent", "College degree"), 
                      V1=c("Yes", "Yes"), V2=c("Yes", "Yes"), 
                      V1.1=c("Yes", "Yes"), V2.1=c("Yes", "Yes"))

# Adding lines informing what models' covariates
part.effect <- did.out.tab.gen[-1, c(1, 2)] %>% 
  cbind(did.out.tab.race[-1, c(1, 2)] ) %>%
  data.frame() %>%
  mutate(V0=c('Reform in 2022', "", "N")) %>% 
  select(V0, V1, V2, V1.1, V2.1) %>% 
  rbind(adlines) 


# Selecting interest outcomes
names(part.effect) <- c("X", "Candidates", "Funding", "Candidates ", "Funding ")

# Getting Latex table:
part.effect %>% 
  as.tbl() %>% 
  rename_with(~ str_replace_all(., "\\.|X", " ")) %>% 
  gt() %>%  
  tab_spanner(label = "Female", columns = 2:3) %>%
  tab_spanner(label = "Afro-Brazilian", columns = 4:5) %>%
  tab_header(title = 'Effect of  on party efforts to support female and afro-Brazilian candidacies with time-varying covariates') %>% 
  # Notes:
  tab_footnote(footnote = "Notes: * p < 0.05, ** p < 0.01, *** p < 0.001.
The tests were conducted using doubly robust approach of the Differences-in-Differences with 
Multiple Time Periods (Callaway & Sant’Anna, 2021). 
  The estimated effects show the impact of approved by the 2022 reform on 
  political parties' efforts to promote female candidates. 
  The dependent variables include the proportion of women and afro-Brazilians 
  within party lists, 
  as well as the campaign funding allocated by parties to those candidates.
  The models include the proportion of female and afro-Brazilian candidates 
  who are incumbents or hold a college degree as a time-varying covariate. 
  The coefficients were estimatted with did R package (Callaway & Sant'Anna, 2021).
                 ") %>% 
  tab_options(heading.title.font.size = 16) %>% 
  opt_vertical_padding(scale = 0) %>% 
  gtsave(filename = file.path(outfolder, "tab.effort.cov.tex"))

# Check the table:
part.effect


# Electoral performance --------------------------------------------------------

# Adding lines informing what models' covariates
adlines <- data.frame(V0=c("Incumbent", "College degree"), 
                      V3=c("Yes", "Yes"), V4=c("Yes", "Yes"))

# Selecting interest outcomes
part.effect <- did.out.tab.gen[-1, c(3:4)] %>% 
  mutate(V0=c('Reform in 2022', "", "N")) %>% 
  select(V0, V3, V4) %>% 
  rbind(adlines)

part.effect <- did.out.tab.race[-1, c(3:4)] %>% 
  mutate(V0=c('Reform in 2022', "", "N")) %>% 
  select(V0, V3, V4) %>% 
  rbind(adlines) %>%
  left_join(part.effect, ., by='V0')

# Replacing outcomes' lables:
names(part.effect) <- c("X", "Votes", "Elected", "Votes ", "Elected ")

# Getting Latex table:
part.effect %>% 
  as.tbl() %>% 
  rename_with(~ str_replace_all(., "\\.|X", " ")) %>% 
  gt() %>%  
  tab_spanner(label = "Female", columns = 2:3) %>%
  tab_spanner(label = "Afro-Brazilian", columns = 4:5) %>%
  tab_header(title = 'Effect of  on electoral performance ofwomen and Afro-Brazilians  with time-varying covariates') %>% 
  # Notes:
  tab_footnote(footnote = "Notes: * p < 0.05, ** p < 0.01, *** p < 0.001.
  The tests were conducted using doubly robust approach of the Differences-in-Differences with 
Multiple Time Periods (Callaway & Sant’Anna, 2021). 
The estimated effects show the impact of  approved by the 2022 reform on 
  electoral performance of female candidates. 
  The dependent variables are the vote share and the number of elected candidates for women and Afro-Brazilians. 
  The models include the proportion of female and Afro-Brazilian candidates who are incumbents or hold a college degree as a time-varying covariate. 
  The coefficients were estimatted with did R package (Callaway & Sant'Anna, 2021).
  ") %>% 
  tab_options(heading.title.font.size = 16) %>% 
  opt_vertical_padding(scale = 0) %>% 
  gtsave(filename = file.path(outfolder, "tab.perform.gen.race.cov.tex"))

# Check the table:
part.effect


################################################################################
### Placebo data ---------------------------------------------------------------

# In this section, placebo tests are run to check whether the intervention impacts
# pre treatment periods

### Tests for gender

# Getting test data:
test.data.gen.pl <- test.data.gen %>% 
  # Replacing outcome values in election t for values in election t-1:
  mutate(election.year=as.character(as.numeric(election.year)+4)) %>% 
  select(state, office, party, 
         election.year, cand.share, terr.ctrl, elect.share, vote.share) %>% 
  rename_at(vars('cand.share', 'terr.ctrl', 'elect.share', 'vote.share'), ~paste0(., ".pl")) %>% 
  left_join(test.data.gen, by=c('state', "office", 'party', 'election.year')) %>% ungroup() %>% 
  filter(election.year!='2006') %>% filter(election.year!='2026')

# Setting tratment, time and id:
test.data.gen.pl <- test.data.gen.pl %>% 
  mutate(treatment=ifelse(office=="Federal Deputy", 1, 0),
         time=as.numeric(election.year),
         id=paste(party, "_", state, "_", office), 
         id=as.numeric(factor(id))) %>% 
  mutate(treatment=ifelse(treatment==1, 2022, 0))

# Running the models for gender:
outvars <- c("cand.share.pl", "vote.share.pl", 'elect.share')
mod.list.gen <- get.did.list(test.data.gen.pl, outvars)

# Getting interest coefficients:
did.out.tab.gen <- get.did.tab(mod.list.gen)
did.out.tab.gen <- did.out.tab.gen %>%
  t() %>% as_tibble() 


### Tests for race
# Same steps had take for race

# Getting test data:
test.data.race.pl <- test.data.race %>%
  mutate(election.year=as.character(as.numeric(election.year)+4)) %>% 
  select(state, office, party, 
         election.year, cand.share, terr.ctrl, elect.share, vote.share) %>% 
  rename_at(vars('cand.share', 'terr.ctrl', 'elect.share', 'vote.share'), ~paste0(., ".pl")) %>%
  left_join(test.data.race, by=c('state', "office", 'party', 'election.year')) %>% ungroup() %>% 
  filter(election.year!='2014') %>% filter(election.year!='2026')

test.data.race.pl <- test.data.race.pl %>%  
  mutate(treatment=ifelse(office=="Federal Deputy", 1, 0),
         time=as.numeric(election.year),
         id=paste(party, "_", state, "_", office), 
         id=as.numeric(factor(id))) %>% 
  mutate(treatment=ifelse(treatment==1, 2022, 0))


# Running the models for race:
outvars <- c("cand.share.pl", "vote.share.pl", "elect.share.pl")
mod.list.race <- get.did.list(test.data.race.pl, outvars)

# Getting interest coefficients:
did.out.tab.race <- get.did.tab(mod.list.race)
did.out.tab.race <- did.out.tab.race %>%
  t() %>% as_tibble() 


# From `did.out.tab` table, Latex tables will be set for the paper as following.


# Placebo: parties' effort -----------------------------------------------------

# Selecting interest outcomes
part.effect <- did.out.tab.gen[-1, 1] %>% 
  mutate(V0=c('Reform in 2022', "", "N")) %>% 
  select(V0, V1)

part.effect <- did.out.tab.race[-1, 1] %>% 
  mutate(V0=c('Reform in 2022', "", "N")) %>% 
  select(V0, V1) %>% 
  rename(V2=V1) %>% 
  left_join(part.effect, ., by='V0')

# Replacing outcomes' lables:
names(part.effect) <- c("X", "Candidates", "Candidates ")

# Getting Latex table:
part.effect %>% 
  as.tbl() %>% 
  rename_with(~ str_replace_all(., "\\.|X", " ")) %>% 
  gt() %>% 
  tab_spanner(label = "Female", columns = 2) %>%
  tab_spanner(label = "Afro-Brazilian", columns = 3) %>%
  tab_header(title = 'Placebo effect of  on party efforts to support female and afro-Brazilian candidacies') %>% 
  # Notes:
  tab_footnote(footnote = "Notes: * p < 0.05, ** p < 0.01, *** p < 0.001.
  The tests were conducted using the Differences-in-Differences. 
  The estimated effects show the impact of  approved by the 2022 reform on 
  electoral performance of female candidates during previous elections. 
  The dependent variables include the proportion of female and Afro-Brazilian candidates. 
  It was not possible to conduct a placebo test for party financing because 
  the presence of only two time periods makes it impossible to observe financing 
  before the pre-treatment period. 
  The coefficients were estimatted with did R package (Callaway & Sant'Anna, 2021).
") %>% 
  tab_options(heading.title.font.size = 16) %>% 
  opt_vertical_padding(scale = 0) %>% 
  gtsave(filename = file.path(outfolder, "tab.effort.gen.race.plac.tex"))

# Check the table:
part.effect


# Placebo: electoral performance -----------------------------------------------

# Selecting interest outcomes
part.effect <- did.out.tab.gen[-1, c(2:3)] %>% 
  mutate(V0=c('Reform in 2022', "", "N")) %>% 
  select(V0, V2, V3)

part.effect <- did.out.tab.race[-1, c(2:3)] %>% 
  mutate(V0=c('Reform in 2022', "", "N")) %>% 
  select(V0, V2, V3) %>% 
  left_join(part.effect, ., by='V0')

# Replacing outcomes' lables:
names(part.effect) <- c("X", "Votes", "Elected", "Votes ", "Elected ")

# Getting Latex table:
part.effect %>% 
  as.tbl() %>% 
  rename_with(~ str_replace_all(., "\\.|X", " ")) %>% 
  gt() %>%  
  tab_spanner(label = "Female", columns = 2:3) %>%
  tab_spanner(label = "Afro-Brazilian", columns = 4:5) %>%
  tab_header(title = 'Placebo effect of  on electoral performance of female candidates') %>% 
  # Notes:
  tab_footnote(footnote = "Notes: * p < 0.05, ** p < 0.01, *** p < 0.001.
  The tests were conducted using the Differences-in-Differences. 
  The estimated effects show the impact of  approved by the 2022 reform on 
  electoral performance of female candidates during previous elections. 
  The dependent variables represent the percentage of votes and elected candidates among women and Afro-Brazilians secured by the parties. 
  The coefficients were estimatted with did R package (Callaway & Sant'Anna, 2021).
") %>% 
  tab_options(heading.title.font.size = 16) %>% 
  opt_vertical_padding(scale = 0) %>% 
  gtsave(filename = file.path(outfolder, "tab.perform.gen.race.plac.tex"))

# Check the table:
part.effect



################################################################################
#  Heterogeneity, political parties---------------------------------------------

# Setting vector with left- and right-wing parties:
leftwing <- c("PSOL", "PSB", "PT", "PDT", "PC DO B", "PCB", "PSTU", "PCO",
              "PV", "CIDADANIA")
rightwing <- c("DC", "PLTB", "UNIAO", "PTB", "PODE", "PSDB", "PATRIOTA", 
               "AGIR", "MDB", "POGRESSISTAS", "PMN", "PL", "AVANTE", "PSC")
center <- c("PV", "CIDADANIA")

#  Heterogeneity, left-wing ----------------------------------------------------

# Pick the ideology:
ideology <- leftwing


### Tests for gender
# Getting test data:
test.data.cs <- test.data.gen %>% 
  filter(party %in% ideology) %>% 
  mutate(treatment=ifelse(office=="Federal Deputy", 1, 0),
         time=as.numeric(election.year),
         id=paste(party, "_", state, "_", office), #
         id=as.numeric(factor(id))) %>% 
  mutate(treatment=ifelse(treatment==1, 2022, 0))

# Running the models for gender:
outvars <- c('cand.share', 'fund.share', 'vote.share', 'elect.share')
mod.list.gen <- get.did.list(test.data.cs, outvars = outvars, covariates = "no.covariates")

# Getting interest coefficients:
left.did.out.tab.gen <- get.did.tab(mod.list.gen)
left.did.out.tab.gen <- left.did.out.tab.gen %>%
  t() %>% as_tibble() 


### Tests for race
# Same steps had take for race:
# Getting test data:
test.data.cs <- test.data.race %>% 
  filter(party %in% ideology) %>% 
  mutate(treatment=ifelse(office=="Federal Deputy", 1, 0),
         time=as.numeric(election.year),
         id=paste(party, "_", state, "_", office), #
         id=as.numeric(factor(id))) %>% 
  mutate(treatment=ifelse(treatment==1, 2022, 0))

# Running the models for race:
outvars <- c('cand.share', 'fund.share', 'vote.share', 'elect.share')
mod.list.race <- get.did.list(test.data.cs, outvars = outvars, covariates = "no.covariates")

# Getting interest coefficients:
left.did.out.tab.race <- get.did.tab(mod.list.race)
left.did.out.tab.race <- left.did.out.tab.race %>%
  t() %>% as_tibble() 



# From `did.out.tab` table, Latex tables will be set for the paper as following.


#  Heterogeneity, right-wing ---------------------------------------------------

# Pick the ideology:
ideology <- rightwing

### Tests for gender
# Getting test data:
test.data.cs <- test.data.gen %>% 
  filter(party %in% ideology) %>% 
  mutate(treatment=ifelse(office=="Federal Deputy", 1, 0),
         time=as.numeric(election.year),
         id=paste(party, "_", state, "_", office), #
         id=as.numeric(factor(id))) %>% 
  mutate(treatment=ifelse(treatment==1, 2022, 0))


# Running the models for gender:
outvars <- c('cand.share', 'fund.share', 'vote.share', 'elect.share')
mod.list.gen <- get.did.list(test.data.cs, outvars = outvars, covariates = "no.covariates")

# Getting interest coefficients:
right.did.out.tab.gen <- get.did.tab(mod.list.gen)
right.did.out.tab.gen <- right.did.out.tab.gen %>%
  t() %>% as_tibble() 


### Tests for race
# Same steps had take for race:
# Getting test data:
test.data.cs <- test.data.race %>% 
  filter(party %in% ideology) %>% 
  mutate(treatment=ifelse(office=="Federal Deputy", 1, 0),
         time=as.numeric(election.year),
         id=paste(party, "_", state, "_", office), #
         id=as.numeric(factor(id))) %>% 
  mutate(treatment=ifelse(treatment==1, 2022, 0))

# Running the models for race:
outvars <- c('cand.share', 'fund.share', 'vote.share', 'elect.share')
mod.list.race <- get.did.list(test.data.cs, outvars = outvars, covariates = "no.covariates")

# Getting interest coefficients:
right.did.out.tab.race <- get.did.tab(mod.list.race)
right.did.out.tab.race <- right.did.out.tab.race %>%
  t() %>% as_tibble() 


# Parties' efforts for female by ideology --------------------------------------

# Selecting interest outcomes
part.effect <- left.did.out.tab.gen[-1, c(1:2)] %>% 
  mutate(V0=c('Reform in 2022', "", "N")) %>% 
  select(V0, V1, V2)

part.effect <- right.did.out.tab.gen[-1, c(1:2)] %>% 
  mutate(V0=c('Reform in 2022', "", "N")) %>% 
  select(V0, V1, V2) %>%
  rename(V3=V1, V4=V2) %>% 
  left_join(part.effect, by="V0") %>% 
  select(V0, V1, V3, V2, V4)

# Replacing outcomes' lables:
names(part.effect) <- c("X", "Left ", "Right ", "Left", "Right")

# Getting Latex table:
part.effect %>% 
  as.tbl() %>% 
  rename_with(~ str_replace_all(., "\\.|X", " ")) %>% 
  gt() %>%  
  tab_spanner(label = "Candidates", columns = 2:3) %>%
  tab_spanner(label = "Funding", columns = 4:5) %>%
  tab_header(title = 'Effect of funding incentives on party efforts to support female candidacies by ideology') %>% 
  # Notes:
  tab_footnote(footnote = "Notes: * p < 0.05, ** p < 0.01, *** p < 0.001.
  The tests were conducted using the Differences-in-Differences. 
  The estimated effects show the impact of funding incentives on 
  parties' efforts to promote female candidates by ideology. 
  The dependent variables include the proportion of women within party lists, 
  as well the campaign funding allocated by parties to female candidates. 
  The coefficients were estimatted with did R package (Callaway & Sant'Anna, 2021).
  ") %>% 
  tab_options(heading.title.font.size = 16) %>% 
  opt_vertical_padding(scale = 0) %>% 
  gtsave(filename = file.path(outfolder, "tab.effort.gen.ideol.tex"))

# Check the table:
part.effect


# Parties' efforts for black by ideology ---------------------------------------

# Selecting interest outcomes
part.effect <- left.did.out.tab.race[-1, c(1:2)] %>% 
  mutate(V0=c('Reform in 2022', "", "N")) %>% 
  select(V0, V1, V2)

part.effect <- right.did.out.tab.race[-1, c(1:2)] %>% 
  mutate(V0=c('Reform in 2022', "", "N")) %>% 
  select(V0, V1, V2) %>%
  rename(V3=V1, V4=V2) %>% 
  left_join(part.effect, by="V0") %>% 
  select(V0, V1, V3, V2, V4)

# Replacing outcomes' lables:
names(part.effect) <- c("X", "Left ", "Right ", "Left", "Right")

# Getting Latex table:
part.effect %>% 
  as.tbl() %>% 
  rename_with(~ str_replace_all(., "\\.|X", " ")) %>% 
  gt() %>%  
  tab_spanner(label = "Candidates", columns = 2:3) %>%
  tab_spanner(label = "Funding", columns = 4:5) %>%
  tab_header(title = 'Effect of funding incentives on party efforts to support afro-Brazilian candidacies by ideology') %>% 
  # Notes:
  tab_footnote(footnote = "Notes: * p < 0.05, ** p < 0.01, *** p < 0.001. 
The tests were conducted using the Differences-in-Differences. 
  The estimated effects show the impact of funding incentives approved by the 2022 reform on 
  parties' efforts to promote afro-Brazilians candidates by ideology. 
  The dependent variables include the proportion of afro-Brazilian within party lists, 
  as well the campaign funding allocated by parties to Black candidates.
  The coefficients were estimatted with did R package (Callaway & Sant'Anna, 2021).
  ") %>% 
  tab_options(heading.title.font.size = 16) %>% 
  opt_vertical_padding(scale = 0) %>% 
  gtsave(filename = file.path(outfolder, "tab.effort.race.ideol.tex"))

# Check the table:
part.effect


# Electoral performance by ideology --------------------------------------------

# Selecting interest outcomes
part.effect.gen <- left.did.out.tab.gen[-1, c(3, 4)] %>% 
  mutate(V0=c('Reform in 2022', "", "N")) %>% 
  select(V0, V3, V4)

part.effect.gen <- right.did.out.tab.gen[-1, c(3, 4)] %>% 
  select(V3, V4) %>% 
  cbind(part.effect.gen, .)

part.effect.race <- left.did.out.tab.race[-1, c(3, 4)] %>% 
  select(V3, V4)

part.effect.race <- right.did.out.tab.race[-1, c(3, 4)] %>% 
  select(V3, V4) %>% 
  cbind(part.effect.race, .)

part.effect <- part.effect.gen %>% cbind(part.effect.race)
  
# Replacing outcomes' lables:
names(part.effect) <- names(part.effect) <- c("X", "Left ", "Right ", "Left", "Right", 
                                              " Left ", " Right ", " Left", " Right")

# Getting Latex table:
part.effect %>% 
  as.tbl() %>% 
  rename_with(~ str_replace_all(., "\\.|X", " ")) %>% 
  gt() %>%  
  tab_spanner(label = "Votes ", columns = 2:3) %>%
  tab_spanner(label = "Elected ", columns = 4:5) %>%
  tab_spanner(label = "Votes", columns = 6:7) %>%
  tab_spanner(label = "Elected", columns = 8:9) %>%
  tab_spanner(label = "Female", columns = 2:5) %>%
  tab_spanner(label = "Afro-Brazilian", columns = 6:9) %>%
  tab_header(title = 'Effect of funding incentives on electoral performance of women and Afro-Brazilians by ideology') %>% 
  # Notes:
  tab_footnote(footnote = "Notes: * p < 0.05, ** p < 0.01, *** p < 0.001.
  The tests were conducted using the Differences-in-Differences. 
  The estimated effects show the impact of  approved by the 2022 reform on 
  electoral performance of female and black candidates by ideology. 
  The dependent variables are the vote share and the number of elected candidates for women and Afro-Brazilians. 
  The coefficients were estimatted with did R package (Callaway & Sant'Anna, 2021).
  ") %>% 
  tab_options(heading.title.font.size = 16) %>% 
  opt_vertical_padding(scale = 0) %>% 
  gtsave(filename = file.path(outfolder, "tab.perform.ideol.tex"))

# Check the table:
part.effect


################################################################################
# Non-competitive candidacies --------------------------------------------------
# In this section, models are ran for competitive and non-competitive candidates 

### Gender sample --------------------------------------------------------------
# Get data in the format required by `did` package:
test.data.share <- test.data.gen %>% 
  mutate(treatment=ifelse(office=="Federal Deputy", 1, 0),
         time=as.numeric(election.year),
         id=paste(party, "_", state, "_", office), 
         id=as.numeric(factor(id))) %>% 
  mutate(treatment=ifelse(treatment==1, 2022, 0)) %>% 
  ungroup() %>% 
  select(election.year, state, office, party,
         treatment, time, id)


# For each .05 vote band, a test is ran:
band <- 0.05
for(i in seq(0, .95, band)){
  print(i)
  
  test.data.loop <- gen.race.cand %>% 
    # Filter the banf of 0.05 relative to the last-elected candidate' vote:
    filter(vote.share >= quantile(last.vote.share, probs = i)) %>% 
    filter(vote.share <= quantile(last.vote.share, probs = (i+band))) %>% 
    # Get number of candidates and funding:
    group_by(election.year, state, office, party, gender) %>% 
    summarise(n.cand=n(), fund=sum(fund, na.rm = T)) %>% 
    # Get the proportion of candidates and funding:
    group_by(election.year, state, office, party) %>% 
    mutate(cand.share=n.cand/sum(n.cand, na.rm = T),
           fund.share=fund/sum(fund, na.rm = T)) %>% 
    ungroup() %>% 
    # Get just information about women:
    filter(gender==1) %>%
    select(-gender, -fund) %>% 
    # Join with `test.data.share` (a format required by `did` package):
    left_join(test.data.share, ., by=c('election.year', 'state', 'office', 'party')) %>% 
    ungroup() %>% 
    # If there was not votes and funding for women, NA values were replaced by 0:
    mutate(cand.share=ifelse(is.na(cand.share), 0, cand.share),
           fund.share=ifelse(is.na(fund.share), 0, fund.share))
  
  if(nrow(test.data.loop)!=6480){print("Problem!")}
  if(nrow(test.data.loop)!=6480){break}

  
  # Running the models  
  mod.gen.cand <- test.data.loop %>% 
    att_gt(yname = "cand.share", gname = "treatment", idname = "id", tname = "time", xformla = ~1, data = .) %>% 
    aggte(type = "simple")
  
  mod.gen.fund <- test.data.loop %>%
    att_gt(yname = "fund.share", gname = "treatment", idname = "id", tname = "time", xformla = ~1, data = .) %>% 
    aggte(type = "simple")
  
  # Getting 
  tab.cand <- data.frame(att=mod.gen.cand$overall.att,
                         conf.low=mod.gen.cand$overall.att-(1.96*mod.gen.cand$overall.se),
                         conf.high = mod.gen.cand$overall.att+(1.96*mod.gen.cand$overall.se))
  
  tab.fund <- data.frame(att=mod.gen.fund$overall.att,
                         conf.low=mod.gen.fund$overall.att-(1.96*mod.gen.fund$overall.se),
                         conf.high = mod.gen.fund$overall.att+(1.96*mod.gen.fund$overall.se))
  
  # Note: Confidence intervals have gotten manually, as ATT - (1.96 * se), 
  # because values from `tidy` function do not correspond with confidence intervals
  # from `aggte` function (did package). To check and compares, run:
  # aggte(mod.gen.cand, type = 'simple')
  # tidy(mod.gen.cand)
  
  if(i==0){
    tab.gen.cand <- tab.cand %>% mutate(band=i)
    tab.gen.fund <- tab.fund %>% mutate(band=i)
  }
  if(i>0){
    tab.gen.cand <- tab.cand %>% mutate(band=i) %>% rbind(tab.gen.cand)
    tab.gen.fund <- tab.fund %>% mutate(band=i) %>% rbind(tab.gen.fund)
  }
  
}


# Getting graphs:
g.quant.cand.gen <- tab.gen.cand %>%
  mutate(band=band*100, band2=band+5,
         band=paste0(band, '-', band2, "%"),
         band=factor(band, levels=rev(band))) %>% 
  ggplot(., aes(x = band, y = att)) + 
  geom_pointrange(aes(ymin = conf.low, ymax = conf.high)) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  theme_bw() +
  scale_y_continuous(breaks=seq(-.05, .10, 0.025), labels=percent) +
  theme(axis.text.x  = element_text(angle=35)) +
  ylab("ATT - Candidates") +
  xlab("Vote share relative to the last place candidate")

g.quant.fund.gen <- tab.gen.fund %>% 
  mutate(band=band*100, band2=band+5,
         band=paste0(band, '-', band2, "%"),
         band=factor(band, levels=rev(band))) %>% 
  ggplot(., aes(x = band, y = att)) + 
  geom_pointrange(aes(ymin = conf.low, ymax = conf.high)) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  theme_bw() +
  scale_y_continuous(breaks=seq(-.05, .10, 0.025), labels=percent) +
  theme(axis.text.x  = element_text(angle=45)) +
  ylab("ATT - Funding") +
  xlab("Vote share relative to the last place candidate")

# Joining graphs:
(g.quant.cand.gen + g.quant.fund.gen)

# Saving:
ggsave(filename = file.path(outfolder, "g.att.vote.share.gen.png"),
       width = 10, height = 3.5)



### Race sample ----------------------------------------------------------------
# Same procedures are adopted in tests for race

test.data.share <- test.data.race %>% 
  mutate(treatment=ifelse(office=="Federal Deputy", 1, 0),
         time=as.numeric(election.year),
         id=paste(party, "_", state, "_", office),
         id=as.numeric(factor(id))) %>% 
  mutate(treatment=ifelse(treatment==1, 2022, 0)) %>% 
  ungroup() %>% 
  select(election.year, state, office, party,
         treatment, time, id)

band <- 0.05
for(i in seq(0, .95, band)){
  print(i)
  
  test.data.loop <- gen.race.cand %>% 
    filter(vote.share >= quantile(last.vote.share, probs = i)) %>% 
    filter(vote.share <= quantile(last.vote.share, probs = (i+band))) %>% 
    group_by(election.year, state, office, party, race) %>% 
    summarise(n.cand=n(), fund=sum(fund, na.rm = T)) %>% 
    group_by(election.year, state, office, party) %>% 
    mutate(cand.share=n.cand/sum(n.cand, na.rm = T),
           fund.share=fund/sum(fund, na.rm = T)) %>% 
    ungroup() %>% 
    filter(race==1) %>%
    select(-race, -fund) %>% 
    left_join(test.data.share, ., by=c('election.year', 'state', 'office', 'party')) %>% 
    ungroup() %>% 
    mutate(cand.share=ifelse(is.na(cand.share), 0, cand.share),
           fund.share=ifelse(is.na(fund.share), 0, fund.share))
  
  if(nrow(test.data.loop)!=nrow(test.data.share)){print("Problem!")}
  if(nrow(test.data.loop)!=nrow(test.data.share)){break}
  
  mod.gen.cand <- test.data.loop %>%
    att_gt(yname = "cand.share", gname = "treatment", idname = "id", tname = "time", xformla = ~1, data = .) %>% 
    aggte(type = "simple")
  
  mod.gen.fund <- test.data.loop %>%
    att_gt(yname = "fund.share", gname = "treatment", idname = "id", tname = "time", xformla = ~1, data = .) %>% 
    aggte(type = "simple")
  
  tab.cand <- data.frame(att=mod.gen.cand$overall.att,
                         conf.low=mod.gen.cand$overall.att-(1.96*mod.gen.cand$overall.se),
                         conf.high = mod.gen.cand$overall.att+(1.96*mod.gen.cand$overall.se))
  
  tab.fund <- data.frame(att=mod.gen.fund$overall.att,
                         conf.low=mod.gen.fund$overall.att-(1.96*mod.gen.fund$overall.se),
                         conf.high = mod.gen.fund$overall.att+(1.96*mod.gen.fund$overall.se))
  
  if(i==0){
    tab.race.cand <- tab.cand %>% mutate(band=i)
    tab.race.fund <- tab.fund %>% mutate(band=i)
  }
  if(i>0){
    tab.race.cand <- tab.cand %>% mutate(band=i) %>% rbind(tab.race.cand)
    tab.race.fund <- tab.fund %>% mutate(band=i) %>% rbind(tab.race.fund)
  }
  
}


g.quant.cand.race <- tab.race.cand %>% 
  mutate(band=band*100, band2=band+5,
         band=paste0(band, '-', band2, "%"),
         band=factor(band, levels=rev(band))) %>% 
  ggplot(., aes(x = band, y = att)) + 
  geom_pointrange(aes(ymin = conf.low, ymax = conf.high)) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  theme_bw() +
  scale_y_continuous(breaks=seq(-.05, .10, 0.025), labels=percent) +
  theme(axis.text.x  = element_text(angle=45)) +
  ylab("ATT - Candidates") +
  xlab("Vote share relative to the last place candidate")

g.quant.fund.race <- tab.race.fund %>% 
  mutate(band=band*100, band2=band+5,
         band=paste0(band, '-', band2, "%"),
         band=factor(band, levels=rev(band))) %>% 
  ggplot(., aes(x = band, y = att)) + 
  geom_pointrange(aes(ymin = conf.low, ymax = conf.high)) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  theme_bw() +
  scale_y_continuous(breaks=seq(-.05, .10, 0.025), labels=percent) +
  theme(axis.text.x  = element_text(angle=45)) +
  ylab("ATT - Funding") +
  xlab("Vote share relative to the last place candidate")

(g.quant.cand.race + g.quant.fund.race)

ggsave(filename = file.path(outfolder, "g.att.vote.share.race.png"),
       width = 10, height = 3.5)



### End ------------------------------------------------------------------------
